﻿using Common.Cache;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Wechat
{
    /// <summary>
    /// 获取公众号JSSDK票证
    /// </summary>
    public class MediaPlatformJSSDK
    {
        private readonly string appid, secret;
        /// <summary>
        /// 获取公众号JSSDK票证
        /// </summary>
        /// <param name="app_id"></param>
        /// <param name="app_secret"></param>
        public MediaPlatformJSSDK(string app_id, string app_secret)
        {
            this.appid = app_id;
            this.secret = app_secret;
        }
        /// <summary>
        /// 获取公众号JSSDK票证
        /// </summary>
        /// <returns></returns>
        public string GetJsTicket()
        {
            string key = $"jsticket:{appid}";
            return FreeRedisCache.Instance.GetOrAdd(key, _ => GetJsTicketFromWechat());
        }
        private JCacheEntry<string> GetJsTicketFromWechat()
        {
            var mpa = new MediaPlatformAuthentication(appid, secret);
            string token = mpa.GetAccessToken();
            string apiUrl = $"http://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={token}";
            var content = HttpHelper.Get<MediaPlatformJsTicket>(apiUrl);
            if (content == null)
            {
                return null;
            }
            return new JCacheEntry<string> { Data = content.Ticket, Expiry = content.GetExpires() };
        }
    }
    public class MediaPlatformJsTicket : MediaPlatformModelBase
    {
        [JsonProperty("ticket")]
        public string Ticket { get; set; }

    }
}
